package com.qf.springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 动态路由过滤器
 * @author zjw
 */
@Component
public class DynamicRouteFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_FORWARD_FILTER_ORDER - 50;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Object run() throws ZuulException {
        // 如果请求中携带了参数dynamic，根据dynamic的值，查询hash结构中serviceId，requestURI
        // 根据serviceId参数决定请求路由到哪个服务
        // 根据path决定请求发送到哪个路径
        //1. requestContext
        RequestContext requestContext = RequestContext.getCurrentContext();

        //2. request
        HttpServletRequest request = requestContext.getRequest();

        //3. 获取参数  --  查询Redis
        String dynamic = request.getParameter("dynamic");
        if(!StringUtils.isEmpty(dynamic)){
            String serviceId = (String) stringRedisTemplate.opsForHash().get(dynamic, "serviceId");
            String path = (String) stringRedisTemplate.opsForHash().get(dynamic, "path");
            //4. 修改路由规则
            requestContext.put(FilterConstants.SERVICE_ID_KEY,serviceId);
            requestContext.put(FilterConstants.REQUEST_URI_KEY,path);
        }

        return null;
    }
}
